import config
import socket
from utils import LogManager
from storage import Storage


class SocketServer:
	def __init__(self, host = "127.0.0.1", port = config.SERVER_PORT):
		self.host = host
		self.port = port
		self.log = LogManager()
		self.storage = Storage()

	def handle_request(self, request):
		ip_inf = self.storage.get(request[1:].upper())
		response = f'HTTP/1.1 200 OK\r\n'
		response += 'Content-Type: text/json; charset=utf-8\r\n'  # 设置编码为UTF-8
		response += '\r\n'
		if ip_inf is not None:
			self.log.log(self.__class__.__name__,
						 "GET {}://{} SUCCESS".format(ip_inf['protocol'], ip_inf['ip_port']))
			response += f'{ip_inf}'
		else:
			response += "{}"
		return response

	def run(self):
		with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
			server_socket.bind((self.host, self.port))
			server_socket.listen()

			self.log.log(self.__class__.__name__, f'Server listening on {self.host}:{self.port}')

			while True:
				client_socket, client_address = server_socket.accept()
				with client_socket:
					data = client_socket.recv(1024)
					if not data:
						continue

					request = data.decode('utf-8').split()[1]
					response = self.handle_request(request)

					client_socket.sendall(response.encode('utf-8'))
